//
//  RootTaBarController.m
//  Sharind
//
//  Created by 杨笑 on 2017/6/21.
//  Copyright © 2017年 杨笑. All rights reserved.
//

#import "RootTaBarController.h"
#import "CustomNavViewController.h"

#import "OrdersViewController.h"
#import "GiftsViewController.h"
#import "QuestionAnswerVC.h"
#import "MyViewController.h"
#import "LoginViewController.h"
#import "SendMessageViewController.h"

static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

@interface RootTaBarController ()
@property(nonatomic,weak)GiftsViewController *giftsVC;
@property (strong, nonatomic) NSDate *lastPlaySoundDate;
@end

@implementation RootTaBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBar.translucent = NO;
    self.tabBar.tintColor = k65ACFE;
    
    OrdersViewController       *vc1 = [OrdersViewController new];
    GiftsViewController        *vc2 = [GiftsViewController new];
    QuestionAnswerVC           *vc3 = [QuestionAnswerVC new];
    MyViewController           *vc4 = [MyViewController new];
    
    self.giftsVC = vc2;
    
    [self setController:vc1 title:@"订单" imageString:@"order" selectedImageString:@"order_select"];
    [self setController:vc2 title:@"密信" imageString:@"gifts" selectedImageString:@"gifts_select"];
    [self setController:vc3 title:@"问答专区" imageString:@"questionAnswer" selectedImageString:@"questionAnswer_select"];
    [self setController:vc4 title:@"我" imageString:@"my" selectedImageString:@"my_select"];
    
    [[NSNotificationCenter defaultCenter]addObserverForName:kLogOutNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kToken];
        [[EMClient sharedClient] logout:YES];
        
        for (CustomNavViewController *vc in self.viewControllers) {
            [vc popToRootViewControllerAnimated:NO];
        }
        self.selectedIndex = 0;
        [vc1 presentViewController:[[LoginViewController alloc]init] animated:YES completion:nil];
    }];
    
}


-(void)setController:(UIViewController *)controller title:(NSString *)title imageString:(NSString *)image selectedImageString:(NSString *)selectedImageString
{
    CustomNavViewController *naVC = [[CustomNavViewController
                                      alloc]initWithRootViewController:controller];
    naVC.tabBarItem.image = [[UIImage imageNamed:image]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    naVC.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImageString]imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    naVC.navigationBar.barTintColor = k65ACFE;
    naVC.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    controller.title = title;
    
    //适配iOS11
    UIImage *backButtonImage = [[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    naVC.navigationBar.backIndicatorImage = backButtonImage;
    naVC.navigationBar.backIndicatorTransitionMaskImage = backButtonImage;
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, 0) forBarMetrics:UIBarMetricsDefault];
    
    [self addChildViewController:naVC];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)jumpToChatList
{
//    if ([self.navigationController.topViewController isKindOfClass:[SendMessageViewController class]]) {
//        //        ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
//        //        [chatController hideImagePicker];
//    }
//    else if(_giftsVC)
//    {
//        [self.navigationController popToViewController:self animated:NO];
//        [self setSelectedViewController:_giftsVC];
//    }
}
- (void)didReceiveUserNotification:(UNNotification *)notification
{
    NSDictionary *userInfo = notification.request.content.userInfo;
    [self pushMessage:userInfo];
}

- (void)didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    [self pushMessage:userInfo];
    
}

-(void)pushMessage:(NSDictionary *)dic
{
    for (CustomNavViewController *vc in self.viewControllers) {
        [vc popToRootViewControllerAnimated:NO];
    }
    self.selectedIndex = 1;
    [_giftsVC pushViewController:[[SendMessageViewController alloc]initWithConversationChatter:[dic objectForKey:@"ConversationChatter"] conversationType:[dic objectForKey:@"MessageType"]] animated:NO];
}

- (void)playSoundAndVibration
{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
}

-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }

    if (self.giftsVC) {
        if (unreadCount > 0) {
            self.giftsVC.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
        }else{
            self.giftsVC.navigationController.tabBarItem.badgeValue = nil;
        }
    }
    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];
    
    [self.giftsVC loadData];
}

- (void)showNotificationWithMessage:(EMMessage *)message
{
//    EMPushOptions *options = [[EMClient sharedClient] pushOptions];

    NSString *isOpen = [Config userDefaultsGetObjectForKey:kIsOpenRemotePush];
    if (isOpen) {
        BOOL on = [isOpen boolValue];
        if (!on) {
            return;
        }
    }
    
    NSString *alertBody = nil;
    alertBody = @"您有一条新消息";
    
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    BOOL playSound = NO;
    if (!self.lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
        self.lastPlaySoundDate = [NSDate date];
        playSound = YES;
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:kMessageType];
    [userInfo setObject:message.conversationId forKey:kConversationChatter];
    
    //发送本地推送
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        if (playSound) {
            content.sound = [UNNotificationSound defaultSound];
        }
        content.body =alertBody;
        content.userInfo = userInfo;
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:content trigger:trigger];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
    }
    else {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate date]; //触发通知的时间
        notification.alertBody = alertBody;
        notification.alertAction = @"打开";
        notification.timeZone = [NSTimeZone defaultTimeZone];
        if (playSound) {
            notification.soundName = UILocalNotificationDefaultSoundName;
        }
        notification.userInfo = userInfo;
        
        //发送通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
